<template>
  <div class="result-page">
    <!-- 导航栏 -->
    <van-nav-bar
      title="搜索结果"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 搜索结果列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell
        v-for="item in result"
        :key="item.art_id"
        :title="item.title"
        @click="goArticleDetail(item.art_id)"
      >
        <template #label>
          <!-- 图片网格 -->
          <van-grid :border="false" :column-num="item.cover.images.length">
            <van-grid-item
              v-for="(img, index) in item.cover.images"
              :key="index"
            >
              <van-image :src="img" />
            </van-grid-item>
          </van-grid>
          <div class="comment">
            <span>{{ item.aut_name }}</span>
            <span>{{ item.comm_count }}评论</span>
            <span>{{ item.pubdate | rTime }}</span>
          </div>
        </template>
      </van-cell>
    </van-list>
  </div>
</template>

<script>
// 引入搜索结果的接口
import { searchContent } from "@/api/search.js";
export default {
  data() {
    return {
      searchKey: "", //搜索关键字
      page: 1, //获取到的搜索数据当前页数
      result: [], //搜索结果
      loading: false, //加载状态
      finished: false //是否全部加载完
    };
  },
  methods: {
    onClickLeft() {
      this.$router.push("/search");
    },
    // 获取搜索结果
    async getResults() {
      try {
        const res = await searchContent({
          page: this.page,
          q: this.searchKey
        });
        console.log(res);
        this.result.push(...res.data.data.results);
        this.page++;
        // 每一次请求完数据，修改加载状态为停止加载
        this.loading = false;
        if (this.result.length === 0) {
          this.finished = true;
        }
      } catch (err) {
        console.log(err);
        this.$toast.fail("加载失败");
        this.finished = true;
      }
    },

    onLoad() {
      this.getResults();
    },
    // 点击每一条文章去往文章详情页
    goArticleDetail(art_id) {
      this.$router.push(`/articledetail/${art_id.toString()}`);
    }
  },
  mounted() {
    this.searchKey = this.$route.query.searchKey;
    this.getResults();
  }
};
</script>
<style lang="less" scoped>
.result-page {
  /deep/.van-nav-bar {
    background-color: #1989fa;
    .van-icon,
    .van-nav-bar__text {
      color: #fff;
    }
    .van-nav-bar__title {
      color: #fff;
    }
  }
  .comment {
    span {
      margin-right: 10px;
    }
  }
}
</style>
